package cn.mvc.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.fast.core.annotation.Parameter;
import org.fast.core.annotation.RequestMapping;
import org.fast.core.annotation.ResponseBody;
import org.fast.ioc.annotation.Controller;
import org.fast.ioc.annotation.Inject;
import org.fast.web.IDBuilder;
import org.fast.web.Pager;
import org.fast.web.render.Renderer;
import org.fast.web.render.TemplateRenderer;
import org.fast.web.render.TextRenderer;

import cn.mvc.exception.ServiceException;
import cn.mvc.model.Category;
import cn.mvc.model.Content;
import cn.mvc.model.Json;
import cn.mvc.model.http.ContentModel;
import cn.mvc.web.service.ContentService;

@Controller
@RequestMapping("/cnt")
public class ContentController {

	@Inject
	private ContentService cntService;
	@Parameter
	private Content cnt;

	@RequestMapping("/add")
	public String add() {
		cnt.setId(IDBuilder.getDateUid());
		try {
			cntService.addContent(cnt);
			return "redirect:/cnt/show/1-4";
		} catch (ServiceException e) {
			return e.getMessage();
		}

	}

	@RequestMapping("/del/{id}")
	@ResponseBody
	public Json del(String id) {
		Json json = new Json();
		try {
			int r = cntService.delContent(id);
			json.setSuccess(r > 0);
			json.setMsg(r > 0 ? "删除成功" : "内容不存在或已删除");
		} catch (ServiceException e) {
			json.setMsg(e.getMessage());
		}
		return json;
	}

	@RequestMapping("/show/{pageNo}-{pageSize}")
	public Renderer show(int pageNo, int pageSize) {
		List<ContentModel> list = new ArrayList<ContentModel>();
		int totalRows;
		try {
			totalRows = cntService.totalContent();
			Pager pager = Pager.getPager(pageNo, pageSize, totalRows);
			list = cntService.showContent(pager);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pager", pager);
			map.put("cntlist", list);
			return new TemplateRenderer("/content.jsp", map);
		} catch (ServiceException e) {
			return new TextRenderer(e.getMessage());
		}

	}

	@RequestMapping("/cate")
	@ResponseBody
	public Json category() {
		Json json = new Json();
		List<Category> list = new ArrayList<Category>();
		try {
			list = cntService.getCategory();
			json.setSuccess(true);
			json.setObj(list);
		} catch (ServiceException e) {
			json.setMsg(e.getMessage());
		}
		return json;
	}

	public ContentService getCntService() {
		return cntService;
	}

	public void setCntService(ContentService cntService) {
		this.cntService = cntService;
	}

	public Content getCnt() {
		return cnt;
	}

	public void setCnt(Content cnt) {
		this.cnt = cnt;
	}

}
